import {
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  message,
  Radio,
  Row,
  TreeSelect,
} from 'antd';
import { useEffect } from 'react';
import { useStatusDictsModel, useSysShowHideDictsModel } from '@/models/dicts';
import { useMenuModel } from '@/models/menu';
import { addMenu, getMenuDetail, updateMenu } from '@/services/menu';

type Props = {
  menuId: string;
  isEdit?: boolean;
  parentId: string;
  onClose?: (refresh: boolean) => void;
};
const App = (props: Props) => {
  const { isEdit, menuId, parentId, onClose = () => {} } = props;
  const [form] = Form.useForm();
  const title = isEdit ? '编辑' : '新增';
  const menuType = Form.useWatch('menuType', form);
  const { menuTree } = useMenuModel();
  const { showHideOptions } = useSysShowHideDictsModel();
  const list = [
    {
      menuId: 0,
      value: 0,
      label: '主类目',
      menuName: '主类目',
      children: menuTree,
    },
  ];
  const { statusOptions } = useStatusDictsModel();
  const getData = async () => {
    const { data } = await getMenuDetail(menuId);
    const { parentId = 0, menuType, ...rest } = data;
    form.setFieldsValue({ menuType });

    setTimeout(() => {
      form.setFieldsValue({
        ...rest,
        menuId,
        menuType,
        parentId: parentId || 0,
      });
    }, 10);
  };
  useEffect(() => {
    if (!isEdit) {
      form.setFieldsValue({
        menuType: 'M',
        menuId: 0,
        parentId: parentId || 0,
      });
      return;
    }
    getData();
  }, [isEdit]);
  const ok = async () => {
    const values = form.getFieldsValue();
    await form.validateFields();
    const { success } = isEdit
      ? await updateMenu({ ...values, menuId })
      : await addMenu({ ...values });
    console.log(values, parentId, menuId);
    if (success) {
      onClose(true);
      message.success(`${isEdit ? '修改' : '添加'}成功`);
      return;
    }
  };
  return (
    <Modal
      width={650}
      open={true}
      title={`${title}菜单`}
      onOk={ok}
      onCancel={() => onClose(false)}
    >
      <Form form={form} labelCol={{ span: 10 }}>
        <Form.Item
          label="上级菜单"
          name="parentId"
          rules={[
            {
              required: true,
            },
          ]}
          labelCol={{ span: 4 }}
        >
          <TreeSelect
            placeholder="请选择上级菜单"
            treeData={list}
            treeDefaultExpandAll
          />
        </Form.Item>
        <Form.Item
          label="菜单类型"
          name="menuType"
          // initialValue={"M"}
          labelCol={{ span: 4 }}
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Radio.Group
            options={[
              {
                label: '目录',
                value: 'M',
              },
              {
                label: '菜单',
                value: 'C',
              },
              {
                label: '按钮',
                value: 'F',
              },
            ]}
          />
        </Form.Item>
        <Row>
          {/* {["M", "C"].includes(menuType) ? (
            <Col span={12}>
              <Form.Item label="菜单图标" name="icon">

                <Input placeholder="请输入菜单图标" />
              </Form.Item>
            </Col>
          ) : null} */}
          {['M', 'C', 'F'].includes(menuType) ? (
            <Col span={12}>
              <Form.Item
                label="显示排序"
                name="orderNum"
                rules={[
                  {
                    required: true,
                  },
                ]}
              >
                <InputNumber
                  placeholder="请输入显示排序"
                  style={{ width: '100%' }}
                  min={0}
                  max={1000}
                />
              </Form.Item>
            </Col>
          ) : null}
          {['M', 'C', 'F'].includes(menuType) ? (
            <Col span={12}>
              <Form.Item
                label="菜单名称"
                name="menuName"
                rules={[
                  {
                    required: true,
                  },
                ]}
              >
                <Input placeholder="请输入菜单名称" max={20} />
              </Form.Item>
            </Col>
          ) : null}
          {['C'].includes(menuType) ? (
            <Col span={12}>
              <Form.Item
                label="路由名称"
                name="routeName"
                tooltip="默认不填则和路由地址相同：如地址为：`user`，则名称为`User`（注意：为避免名字的冲突，特殊情况下请自定义，保证唯一性）"
              >
                <Input placeholder="请输入路由名称" />
              </Form.Item>
            </Col>
          ) : null}
          {['M', 'C'].includes(menuType) ? (
            <Col span={12}>
              <Form.Item
                label="是否外链"
                name="isFrame"
                initialValue={'1'}
                tooltip="选择是外链则路由地址需要以`http(s)://`开头"
              >
                <Radio.Group
                  options={[
                    {
                      label: '是',
                      value: '0',
                    },
                    {
                      label: '否',
                      value: '1',
                    },
                  ]}
                />
              </Form.Item>
            </Col>
          ) : null}
          {['M', 'C'].includes(menuType) ? (
            <Col span={12}>
              <Form.Item
                rules={[
                  {
                    required: true,
                  },
                ]}
                label="路由地址"
                name="path"
                tooltip="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"
              >
                <Input placeholder="请输入路由地址" max={500} />
              </Form.Item>
            </Col>
          ) : null}
          {['C'].includes(menuType) ? (
            <Col span={12}>
              <Form.Item label="组件路径" name="component">
                <Input placeholder="请输入组件路径" />
              </Form.Item>
            </Col>
          ) : null}
          {['C', 'F'].includes(menuType) ? (
            <Col span={12}>
              <Form.Item
                label="权限字符"
                name="perms"
                tooltip="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
              >
                <Input placeholder="请输入权限字符" />
              </Form.Item>
            </Col>
          ) : null}
          {['C'].includes(menuType) ? (
            <Col span={12}>
              <Form.Item
                label="路由参数"
                name="query"
                tooltip='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`'
              >
                <Input placeholder="请输入路由参数" />
              </Form.Item>
            </Col>
          ) : null}
          {['C'].includes(menuType) ? (
            <Col span={12}>
              <Form.Item
                label="是否缓存"
                name="isCache"
                tooltip="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致"
              >
                <Radio.Group
                  options={[
                    {
                      label: '是',
                      value: 1,
                    },
                    {
                      label: '否',
                      value: 0,
                    },
                  ]}
                />
              </Form.Item>
            </Col>
          ) : null}
          {['M', 'C', 'F'].includes(menuType) ? (
            <Col span={12}>
              <Form.Item
                label="显示状态"
                name="visible"
                initialValue={'0'}
                tooltip="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
              >
                <Radio.Group options={showHideOptions} />
              </Form.Item>
            </Col>
          ) : null}

          {['M', 'C'].includes(menuType) ? (
            <Col span={12}>
              <Form.Item
                label="菜单状态"
                name="status"
                initialValue={'0'}
                tooltip="选择停用则路由将不会出现在侧边栏，也不能被访问"
              >
                <Radio.Group options={statusOptions} />
              </Form.Item>
            </Col>
          ) : null}
        </Row>
      </Form>
    </Modal>
  );
};
export default App;
